import React, { useEffect, useState } from 'react';
import type { MenuProps } from 'antd';
import { Menu } from 'antd';
import { useNavigate } from 'react-router-dom';
import { RouterKeys, routersData } from '@/router/config';
import usePathKey from '@/hooks/usePathKey';
import { select_menu } from '@/redux/slice/user';
import { useAppSelector } from '@/redux';

type MenuItem = {
  label: string;
  key: string;
  path: string;
};
const App: React.FC = () => {
  //当前的key
  const [current, setCurrent] = useState('');
  const navigate = useNavigate();
  const menus: MenuItem[] = useAppSelector(select_menu);
  const path_key = usePathKey();

  const menuData = menus.map((item) => {
    return {
      label: item.label,
      key: item.key,
      path: item.path,
    };
  });
  //点击跳转对应路由页面
  const onClick: MenuProps['onClick'] = (e) => {
    console.log('click ', e);
    setCurrent(e.key);
    navigate(routersData[e.key as RouterKeys].path);
  };

  //页面组件初始化的时候,设置对应菜单的key
  useEffect(() => {
    if (path_key) {
      setCurrent(path_key);
    }
  }, []);

  return (
    <Menu onClick={onClick} selectedKeys={[current]} mode="horizontal" items={menuData} />
  );
};

export default App;
